package sanshi.contect.udpstarter.handler;

import ch.qos.logback.core.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sanshi.contect.udpstarter.service.PiledUpMsgHandler;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ProductMsgHandler {

    private final LinkedBlockingQueue<byte[]> recvLinkedBlockingQueue;


    @Autowired
    private PiledUpMsgHandler piledUpMsgHandler;

    public ProductMsgHandler(LinkedBlockingQueue<byte[]> recvLinkedBlockingQueue) {
        this.recvLinkedBlockingQueue = recvLinkedBlockingQueue;
    }

    public void saveMsg(byte[] data){
        try {
            //添加数据到队列，如果队列满了，阻塞timeout时间，如果阻塞一段时间，依然没添加进入，返回false
            boolean result = recvLinkedBlockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if (!result){
                piledUpMsgHandler.piledUp(data);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("===========================>数据存储成功<===========================");
    }
}
